
<template>  
  <div 
    class="gems-switch"
    :class="{
      [`gems-switch--${size}`]: size,
      'is-disabled': disabled,
      'is-checked': checked,
    }"
     @click="switchValue"
  >
    <input 
      class="gems-switch__input"
      type="checkbox" 
      role="switch"
      :name="name"
      :disabled="disabled"
      ref="input"
      v-model="innerValue"
      @keydown.enter="switchValue"
    />
    <div class="gems-switch__core">
      <div class="gems-switch__core-inner">
        <span v-if="activeText || inactiveText" class="gems-switch__core-inner-text">
          {{ checked ? activeText : inactiveText  }}
        </span>
      </div>
      <div class="gems-switch__core-action">
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, inject } from 'vue'
import type { SwtichProps, SwtichEmits } from './types'
import { formItemContextKey } from '../../components/Form/types';

// Form表单项上下文，用于验证表单数据是否符合验证规则
const formItemContext = inject(formItemContextKey, null)
const runValidation = (trigger?: string) => {
  if (formItemContext) {
    formItemContext.validate(trigger).catch((e) => console.log(e.errors))
  }
}

defineOptions({
  name: 'GemsSwitch',
  inheritAttrs: false,
})
const props = withDefaults(defineProps<SwtichProps>(), {
  activeValue: true,
  inactiveValue: false,
})
const emits = defineEmits<SwtichEmits>()  

const input = ref<HTMLInputElement>()
const innerValue = ref(props.modelValue)
// 现在是否被选中
const checked = computed(() => innerValue.value === props.activeValue)

const switchValue = () => {
  if (props.disabled) return
  const newValue= checked.value ? props.inactiveValue : props.activeValue
  innerValue.value  = newValue
  emits('update:modelValue', newValue)
  emits('change', newValue)
  runValidation('change')
}

onMounted(() => {
  input.value!.checked = checked.value
})
watch(checked, (value) => {
  input.value!.checked = value
})

watch(() => props.modelValue, (value) => {
  innerValue.value = value
})



</script>